package com.coy.whatsup757;

import java.io.IOException;
import java.util.Calendar;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;

public class whatsup extends Activity {

	final HttpClient client = new DefaultHttpClient();
	String thecondensedlist[];
	Integer day, month, year;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Calendar rightNow = Calendar.getInstance();
		year = rightNow.get(Calendar.YEAR);
		month = rightNow.get(Calendar.MONTH) + 1;
		day = rightNow.get(Calendar.DAY_OF_MONTH);

		Button setit = (Button) findViewById(R.id.Button02);
		setit.setText(month.toString() + "/" + day.toString() + "/"
				+ year.toString());

		// Clear out condensedlist for orientation swap
		thecondensedlist = null;

		Button sendit = (Button) findViewById(R.id.Button02);
		sendit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				// Check connectivity

				Calendar c = Calendar.getInstance();

				int cyear = c.get(Calendar.YEAR);

				int cmonth = c.get(Calendar.MONTH);

				int cday = c.get(Calendar.DAY_OF_MONTH);

				DatePickerDialog dpd = new DatePickerDialog(whatsup.this,
						new DatePickerDialog.OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker arg0, int arg1,
									int arg2, int arg3) {
								year = arg1;
								month = arg2 + 1;
								day = arg3;
								Button setit = (Button) findViewById(R.id.Button02);
								setit.setText(month.toString() + "/"
										+ day.toString() + "/"
										+ year.toString());

							}
						}, cyear, cmonth, cday);
				dpd.show();

			}
		});

		Button search = (Button) findViewById(R.id.Button01);
		search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Run thread

				// Handle to ConnectivityManager so we can check for internet
				// connection.
				ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

				if (!connec.getNetworkInfo(0).isConnected()) {
					Toast.makeText(whatsup.this,
							"No internet connection found!", 5000).show();
				} else {
					new processdownload().execute();
				}
			}

		});

	}

	private class processdownload extends AsyncTask<Void, Void, Void> { // params.
		// progress.
		// result,
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = ProgressDialog.show(whatsup.this, "Searching...",
					"Please wait while we locate the events...", true);
		}

		protected Void doInBackground(Void... params) {
			// THIS IS WHERE THE MAIN WORK IS PROCESSED OFF SEPARATE THREAD!

			thecondensedlist = null; // CLEAR OLD DATA OUT.

			// VBNIGHTLIFE.COM
			String vb[] = { "--------------------------", "VBNightLife.com",
					"--------------------------" };
			if (thecondensedlist != null) {
				thecondensedlist = concat(getVBNightLife(year, month, day),
						thecondensedlist);
				thecondensedlist = concat(vb, thecondensedlist);
			} else {
				thecondensedlist = getVBNightLife(year, month, day);
				thecondensedlist = concat(vb, thecondensedlist);
			}

			// NORFOLKNIGHTLIFE.COM
			String nor[] = { "--------------------------",
					"NorfolkNightLife.com", "--------------------------" };
			if (thecondensedlist != null) {
				thecondensedlist = concat(
						getNorfolkNightLife(year, month, day), thecondensedlist);
				thecondensedlist = concat(nor, thecondensedlist);
			} else {
				thecondensedlist = getNorfolkNightLife(year, month, day);
				thecondensedlist = concat(nor, thecondensedlist);
			}

			// HAMPTONROADS.COM
			String hrcom[] = { "--------------------------",
					"HamptonRoads.com", "--------------------------" };
			if (thecondensedlist != null) {
				thecondensedlist = concat(getHREvents(year, month, day),
						thecondensedlist);
				thecondensedlist = concat(hrcom, thecondensedlist);
			} else {
				thecondensedlist = getHREvents(year, month, day);
				thecondensedlist = concat(hrcom, thecondensedlist);
			}

			return null;
		}

		protected void onPostExecute(Void v) {
			// Post results to UI.

			ListView lv = (ListView) findViewById(R.id.ListView01);
			lv.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
					R.layout.list_item, thecondensedlist));
			lv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapter, View v,
						int position, long id) {
					// TODO Auto-generated method stub
					startActivity(new Intent(Intent.ACTION_VIEW, Uri
							.parse("http://www.google.com/search?q="
									+ adapter.getItemAtPosition(position)
											.toString())));

				}

			});
			pd.dismiss();
			Toast.makeText(
					whatsup.this,
					"Events for " + month.toString() + "/" + day.toString()
							+ "/" + year.toString(), 5000).show();

		}

	}

	public String[] getVBNightLife(Integer year, Integer month, Integer day) {
		String[] vblife = { "http://vbnightlife.com/events/event/listByDate?date="
				+ year.toString()
				+ "-"
				+ month.toString()
				+ "-"
				+ day.toString() };
		String theHTML = getHTMLsrc(vblife[0]);
		// Get URL for the ALL EVENTS article and load it into site
		// variable.

		// stripDown(thelist).split("\n")

		vblife = (stripDown(getHTMLsrc(getAllEventsLink(theHTML)))).split("\n");

		return vblife;
	}

	public String[] getNorfolkNightLife(Integer year, Integer month, Integer day) {
		String[] nrflife = { "http://norfolknightlife.com/events/event/listByDate?date="
				+ year.toString()
				+ "-"
				+ month.toString()
				+ "-"
				+ day.toString() };
		String theHTML = getHTMLsrc(nrflife[0]);

		nrflife = (stripDownNor(getHTMLsrc(getAllEventsLinkNor(theHTML))))
				.split("\n");

		return nrflife;
	}

	public String stripDown(String thehtml) {
		// PRE/POST - remove html characters from the string.

		String themainlist[] = thehtml.split("<p><p>");
		themainlist[1] = (String) themainlist[1].substring(0,
				themainlist[1].indexOf("<ul class="));
		themainlist[1] = themainlist[1].replaceAll("<br/>", "\n");
		themainlist[1] = themainlist[1].replaceAll("<br />", "\n");
		themainlist[1] = themainlist[1].replaceAll("<p>", "\n");
		themainlist[1] = themainlist[1].replaceAll("</p>", "\n");
		themainlist[1] = themainlist[1].replaceAll("&#039;", "'");
		themainlist[1] = themainlist[1].replaceAll("&amp;", "&");
		themainlist[1] = themainlist[1].replaceAll("\n\n", "\n");

		while (themainlist[1].indexOf("<a") > -1) { // Strips out link at top
			Integer linkstartpos = themainlist[1].indexOf("<a");
			Integer linkendpos = themainlist[1].indexOf("</a>", linkstartpos);
			themainlist[1] = themainlist[1].substring(0, linkstartpos)
					+ themainlist[1].substring(linkendpos + 4,
							themainlist[1].length());
		}

		return themainlist[1];
	}

	public String stripDownNor(String thehtml) {
		// PRE/POST - remove html characters from the string.

		String themainlist[] = thehtml.split("<div class=\"xg_module_body\">");
		themainlist[1] = (String) themainlist[1].substring(0,
				themainlist[1].indexOf("<ul class="));
		themainlist[1] = themainlist[1].replaceAll("<br/>", "\n");
		themainlist[1] = themainlist[1].replaceAll("<br />", "\n");
		themainlist[1] = themainlist[1].replaceAll("<p>", "\n");
		themainlist[1] = themainlist[1].replaceAll("</p>", "\n");
		themainlist[1] = themainlist[1].replaceAll("&#039;", "'");
		themainlist[1] = themainlist[1].replaceAll("&amp;", "&");
		themainlist[1] = themainlist[1].replaceAll("\n\n", "\n");

		while (themainlist[1].indexOf("<a") > -1) { // Strips out link at top
			Integer linkstartpos = themainlist[1].indexOf("<a");
			Integer linkendpos = themainlist[1].indexOf("</a>", linkstartpos);
			themainlist[1] = themainlist[1].substring(0, linkstartpos)
					+ themainlist[1].substring(linkendpos + 4,
							themainlist[1].length());
		}

		return themainlist[1];
	}

	public String getHTMLsrc(String url) {
		// PRE/POST - Get the source code for url provided. return error if no
		// internet.

		String site = null;
		try {
			site = Http.get(url).use(client).asString();

		} catch (IOException e) {
			Toast.makeText(this, "Unable to connect to internet!", 50000)
					.show();
			e.printStackTrace();
			// super.finish(); - NEED TO FIX THIS SITUATION.

		}
		return site;
	}

	public String getAllEventsLink(String url) {
		// PRE/POST - Pull the date's event link from source.

		String thelink = null;
		Integer urlstartpos = url.indexOf(
				"http://vbnightlife.com/events/all-events-click-here", 0); // this
		// doesnt
		// work
		// for
		// norfolk
		Integer urlendpos = url.indexOf("\"", urlstartpos);

		if (urlendpos > -1) {
			thelink = url.substring(urlstartpos, urlendpos);
		}

		return thelink;
	}

	public String getAllEventsLinkNor(String url) {
		// PRE/POST - Pull the date's event link from source.

		String thelink = null;
		Integer urlstartpos = url.indexOf(
				"http://norfolknightlife.com/events/all-events-click-here", 0); // this
		// doesnt
		// work
		// for
		// norfolk
		Integer urlendpos = url.indexOf("\"", urlstartpos);

		if (urlendpos > -1) {
			thelink = url.substring(urlstartpos, urlendpos);
		}

		return thelink;
	}

	public String[] concat(String[] A, String[] B) {
		// Precondition: both strings cannot be NULL!
		String[] C = new String[A.length + B.length];
		System.arraycopy(A, 0, C, 0, A.length);
		System.arraycopy(B, 0, C, A.length, B.length);

		return C;
	}

	public String[] getHREvents(Integer year, Integer month, Integer day) {
		// http://hamptonroads.com/events/date/2010/12/14?cid=eg
		String[] hrsite = { "http://hamptonroads.com/events/date/"
				+ year.toString() + "/" + month.toString() + "/"
				+ day.toString() + "?cid=eg" };
		String theHTML = getHTMLsrc(hrsite[0]);
		// todo:Check null ptr exception.
		hrsite = stripHRDown(theHTML);
		hrsite[0] = "";
		return hrsite;
	}

	public String[] stripHRDown(String thehtml) {
		// Look for <td class="dates">
		String thedirty = null;
		String[] thesplithtml = thehtml.split("<td class=\"dates\"");

		for (Integer i = 1; i < thesplithtml.length; i++) {
			Integer startpos = thesplithtml[i].indexOf("\">") + 2;
			Integer endpos = thesplithtml[i].indexOf("</a>");
			Integer fakestartpos = thesplithtml[i].indexOf("\">", endpos) + 2;
			Integer lstartpos = thesplithtml[i].indexOf("\">", fakestartpos) + 2;
			Integer lendpos = thesplithtml[i].indexOf("</a>", lstartpos);
			thedirty = thedirty + "\n"
					+ thesplithtml[i].substring(lstartpos, lendpos) + " - "
					+ thesplithtml[i].substring(startpos, endpos);
			// TODO: find and add venue for this date. ex. "blah - blah"

		}
		thedirty = thedirty.replaceAll("<br/>", "\n");
		thedirty = thedirty.replaceAll("<br />", "\n");
		thedirty = thedirty.replaceAll("<p>", "\n");
		thedirty = thedirty.replaceAll("</p>", "\n");
		thedirty = thedirty.replaceAll("&#039;", "'");
		thedirty = thedirty.replaceAll("&amp;", "&");
		thedirty = thedirty.replaceAll("\n\n", "\n");

		return thedirty.split("\n");
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection from the options menu.
		switch (item.getItemId()) {
		case R.id.about:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("What's up 757?\n\nSearches Hampton Roads popular web sources for things to do!\n\n�2010 by Chris Coykendall");
			builder.setCancelable(false);
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							arg0.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.show();

			return true;
		case R.id.share:
			Intent sendIntent = new Intent(Intent.ACTION_VIEW);
			sendIntent
					.putExtra(
							"sms_body",
							"What's up in 757? - http://market.android.com/search?q=pname:com.coy.whatsup757");
			sendIntent.setType("vnd.android-dir/mms-sms");
			startActivity(sendIntent);
			return true;
		case R.id.exit:
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}